package cn.itcast.jx.action;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;

import cn.itcast.jx.common.SysConstant;
import cn.itcast.jx.domain.User;
import cn.itcast.jx.util.UtilFuns;

/**
 * 
 * @Description:
 * @author:     传智播客 java学院    传智.袁新奇
 * @version:    1.0
 * @Company:    http://java.itcast.cn 
 * @date:       2016年9月17日
 */
public class LoginAction extends BaseAction {

	private static final long serialVersionUID = 1L;

	private String username;
	private String password;

	//SSH传统登录方式
	public String login() throws Exception {
		Subject subject = SecurityUtils.getSubject();
		
		boolean isLogin = subject.isAuthenticated();
		if(isLogin) {
			return SUCCESS;
		}
		
		if(UtilFuns.isEmpty(username)){
			return LOGIN;
		}
		try {
			//shiro认证过程-
			//1 获取Subject对象
			//2 实现登录过程:封装用户在页面上提交的用户名和密码
			UsernamePasswordToken token = new UsernamePasswordToken(username, password);
			//就会进入Realm域中的认证方法
			subject.login(token);
			//3将封装好的用户名和密码交给shiro安全框架并实现登录
			//4 当认证成功后，要将Shiro中保存的用户对象取出来
			User user =  (User) subject.getPrincipal();
			//5 将用户对象放入session域中
			session.put(SysConstant.CURRENT_USER_INFO, user);
			// 6 跳页面
		} catch (Exception e) {
			request.put("errorInfo", "对不起,登录失败,用户名或密码错误!");
		
			return LOGIN;
		}
	return SUCCESS;

	}
	
	public String logout() {
		session.remove("SysConstant.CURRENT_USER_INFO");
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return "logout";
	}
	
	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}

